package com.itheima.bird;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.itheima.jdbc.Account;


public class BirdDaoImpl implements BirdDao {

	// 声明JdbcTemplate属性及其setter方法
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	@Override
	public int addBird(Bird bird) {
		// TODO Auto-generated method stub
		// 定义SQL
		String sql = "insert into bird(id,type) value(?,?)";
		// 定义数组来存放SQL语句中的参数
		Object[] obj = new Object[] { 
				bird.getId(),
				bird.getType()
         };
		// 执行添加操作，返回的是受SQL语句影响的记录条数
		int num = this.jdbcTemplate.update(sql, obj);
		return num;
	}

	@Override
	public int updateBird(Bird bird) {
		// TODO Auto-generated method stub
		// 定义SQL
		String sql = "update bird set id=?,type=? where id = ?";
		// 定义数组来存放SQL语句中的参数
		Object[] params = new Object[] { 
				bird.getId(),
				bird.getType(),
				bird.getId()
          };
		// 执行更新操作，返回的是受SQL语句影响的记录条数
		int num = this.jdbcTemplate.update(sql, params);
		return num;
	}

	@Override
	public int deleteBird(int id) {
		// TODO Auto-generated method stub
		// 定义SQL
				String sql = "delete  from bird where id = ? ";
				// 执行删除操作，返回的是受SQL语句影响的记录条数
				int num = this.jdbcTemplate.update(sql, id);
				return num;
	}

	@Override
	public Bird findBirdById(int id) {
		// TODO Auto-generated method stub
	    //定义SQL语句
	    String sql = "select * from bird where id = ?";
	    // 创建一个新的BeanPropertyRowMapper对象
	    RowMapper<Bird> rowMapper = 
	new BeanPropertyRowMapper<Bird>(Bird.class);
	    // 将id绑定到SQL语句中，并通过RowMapper返回一个Object类型的单行记录
	    return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
	}

	@Override
	public List<Bird> findAllBird() {
		// TODO Auto-generated method stub
	    // 定义SQL语句
	    String sql = "select * from bird";
	    // 创建一个新的BeanPropertyRowMapper对象
	    RowMapper<Bird> rowMapper = 
	new BeanPropertyRowMapper<Bird>(Bird.class);
	    // 执行静态的SQL查询，并通过RowMapper返回结果
	    return this.jdbcTemplate.query(sql, rowMapper);
	}

}
